package fw.qaz.asmx.reader;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

import fw.qaz.asmx.reader.adapter.item.BookMarkItem;
import fw.qaz.asmx.reader.utils.Convertor;
import fw.qaz.asmx.reader.utils.FileProcess;

public abstract class SettingCenter
{
    public static void setFirstUse(Context cxt, boolean tf)
    {
        cxt.getSharedPreferences("preferences", Context.MODE_PRIVATE).edit()
           .putBoolean("first_use", tf).apply();
    }

    public static boolean isFirstUse(Context cxt)
    {
        SharedPreferences sp = cxt.getSharedPreferences("preferences", Context.MODE_PRIVATE);
        return sp.getBoolean("first_use", true);
    }

    public static void setFontSize(Context cxt, int size)
    {
        cxt.getSharedPreferences("preferences", Context.MODE_PRIVATE).edit()
           .putInt("font_size", size).apply();
    }

    public static int getFontSize(Context cxt)
    {
        int sp = cxt.getSharedPreferences("preferences", Context.MODE_PRIVATE)
                    .getInt("font_size", 12);
        return Convertor.sp2px(cxt, sp);
        //你可以在这里条用低下的方法获取12~36的int
        //然后在转换成你想要的任何东西

    }


    //求别改这方法
    public static int getFontSizeMAO(Context cxt)
    {

        int MAOINT = cxt.getSharedPreferences("preferences", Context.MODE_PRIVATE)
                .getInt("font_size",12);
        return MAOINT;
    }

    public static void setFontColor(Context cxt, int r, int g, int b)
    {
        cxt.getSharedPreferences("preferences", Context.MODE_PRIVATE).edit()
           .putInt("fontColorRed", r)
           .putInt("fontColorGreen", g)
           .putInt("fontColorBlue", b)
           .apply();
    }

    public static int getFontColor(Context cxt)
    {
        SharedPreferences sp = cxt.getSharedPreferences("preferences", Context.MODE_PRIVATE);
        int r = sp.getInt("fontColorRed", 0);
        int g = sp.getInt("fontColorGreen", 0);
        int b = sp.getInt("fontColorBlue", 0);
        return Color.rgb(r, g, b);
    }

    public static void setBackgroundType(Context cxt, int type)
    {
        cxt.getSharedPreferences("preferences", Context.MODE_PRIVATE)
           .edit()
           .putInt("", type)
           .apply();
    }

    public static int getBackgroundType(Context cxt)
    {
        return 0;
        //return cxt.getSharedPreferences("preferences", Context.MODE_PRIVATE).getInt("",0);
    }

    public static void setBackgroundColor(Context cxt, int r, int g, int b)
    {
        cxt.getSharedPreferences("preferences", Context.MODE_PRIVATE).edit()
           .putInt("bgColorRed", r)
           .putInt("bgColorGreen", g)
           .putInt("bgColorBlue", b)
           .apply();
    }

    public static int getBackgroundColor(Context cxt)
    {
        SharedPreferences sp = cxt.getSharedPreferences("preferences", Context.MODE_PRIVATE);
        int r = sp.getInt("bgColorRed", 255);
        int g = sp.getInt("bgColorGreen", 255);
        int b = sp.getInt("bgColorBlue", 255);
        return Color.rgb(r, g, b);
    }

    public static void setPreDefineBackgroundPic(Context cxt, int id)
    {
        cxt.getSharedPreferences("preferences", Context.MODE_PRIVATE)
           .edit()
           .putInt("", id)
           .apply();
    }

    public static Bitmap getPreDefineBackgroundPic()
    {
        return null;
    }

    public static void setSelfDefineBackgroundPic(Context cxt, String path)
    {
        cxt.getSharedPreferences("preferences", Context.MODE_PRIVATE)
           .edit()
           .putString("", path)
           .apply();
    }

    public static Bitmap getSelfDefineBackgroundPic()
    {
        return null;
    }

    public static void setAppDisplayLanguage(Context cxt, int id)
    {
        cxt.getSharedPreferences("preferences", Context.MODE_PRIVATE)
           .edit()
           .putInt("", id)
           .apply();
    }

    public static int getAppDisplayLanguage(Context cxt)
    {
        return cxt.getSharedPreferences("preferences", Context.MODE_PRIVATE).getInt("lang_id", 0);
    }

    //-----------------------------------------书签相关--------------------------------------------------------------
    //演示在 SettingDialog 里的saveSettings 方法内
    //保存一个书签  Contex ，书的路径 ，摘要， 进度
    public static void saveBookmark(Context ctx, String name, int id, String comment, int progress)
    {
        String jsonString = getJsonStringFromFile(ctx);//读取jsonstring
        ArrayList<BookMarkItem> marks = readBookMarkJson(jsonString);//解析到marks里
        //遍历添加
        boolean hasThisBook = false;
        for (int i = 0; i < marks.size(); i++)
        {
            if (marks.get(i).path.equals(name))
            {
                marks.get(i).addMark(id, comment, progress); //添加新书签
                hasThisBook = true;
            }
        }
        //如果书不存在,新开一条记录
        if (!hasThisBook)
        {
            marks.add(new BookMarkItem(id, name, comment, progress));
        }
        String newStr = changeToStrFromBookMarkList(marks);
        //写回去
        FileProcess.writeFile(getFile(ctx).getAbsolutePath(), newStr.getBytes(), false);
        //Toast.makeText(ctx, "信息" + "书签保存成功", Toast.LENGTH_LONG).show();
    }

    //取出进度最高的
    public static long getMaxProgress(Context ctx, String name)
    {
        String jsonString = getJsonStringFromFile(ctx);//读取jsonstring
        ArrayList<BookMarkItem> marks = readBookMarkJson(jsonString);//解析到marks里
        //遍历获取最高值
        for (int i = 0; i < marks.size(); i++)
        {
            if (marks.get(i).path.equals(name))
            {
                return marks.get(i).getMaxProgress();
            }
        }
        return 0;
    }

    //取出一本书的所有书签
    public static BookMarkItem getOneBooksAllMarks(Context ctx, String name)
    {
        String jsonString = getJsonStringFromFile(ctx);//读取jsonstring
        ArrayList<BookMarkItem> marks = readBookMarkJson(jsonString);//解析到marks里
        //遍历获取最高值
        for (int i = 0; i < marks.size(); i++)
        {
            if (marks.get(i).path.equals(name))
            {
                return marks.get(i);
            }
        }
        return null;
    }

    //删除某本书的一个进度
    public static void deleteOneMark(Context ctx, String name, int CommentId)
    {
        String jsonString = getJsonStringFromFile(ctx);//读取jsonstring
        ArrayList<BookMarkItem> marks = readBookMarkJson(jsonString);//解析到marks里
        //遍历删除
        for (int i = 0; i < marks.size(); i++)
        {
            if (marks.get(i).path.equals(name))
            {
                marks.get(i).removeMarkById(CommentId);
            }
        }
        String newStr = changeToStrFromBookMarkList(marks);
        //写回去
        FileProcess.writeFile(getFile(ctx).getAbsolutePath(), newStr.getBytes(), false);
        //Toast.makeText(ctx, "信息" + "书签保存成功", Toast.LENGTH_LONG).show();
    }

    //修改某本书的一个进度
    public static void editOneMark(Context ctx, String name, int CommentId, String newComment)
    {
        String jsonString = getJsonStringFromFile(ctx);//读取jsonstring
        ArrayList<BookMarkItem> marks = readBookMarkJson(jsonString);//解析到marks里
        //遍历修改
        for (int i = 0; i < marks.size(); i++)
        {
            if (marks.get(i).path.equals(name))
            {
                marks.get(i).renameComment(CommentId, newComment);
            }
        }
        String newStr = changeToStrFromBookMarkList(marks);
        //写回去
        FileProcess.writeFile(getFile(ctx).getAbsolutePath(), newStr.getBytes(), false);
    }

    //删除某本书（不是删除书，从阅读记录里删除）
    public static void deleteBookMark(Context ctx, String name)
    {
        String jsonString = getJsonStringFromFile(ctx);//读取jsonstring
        ArrayList<BookMarkItem> marks = readBookMarkJson(jsonString);//解析到marks里
        //遍历删除
        for (int i = 0; i < marks.size(); i++)
        {
            if (marks.get(i).path.equals(name))
            {
                marks.remove(i);
            }
        }
        String newStr = changeToStrFromBookMarkList(marks);
        //写回去
        FileProcess.writeFile(getFile(ctx).getAbsolutePath(), newStr.getBytes(), false);
    }

    //获取字符串
    private static String getJsonStringFromFile(Context ctx)
    {
        String jsonString = "";
        File bookMarkJsonFile = null;   //        读取或者写入文件
        try
        {
            bookMarkJsonFile = getFile(ctx);
            if (bookMarkJsonFile.exists())//存在读取，不存在则创建
            {
                jsonString = new String(FileProcess.readFile(bookMarkJsonFile.getAbsolutePath()));
            }
            else
            {
                FileProcess.writeFile(bookMarkJsonFile.getAbsolutePath(), "[]".getBytes(), false);
                jsonString = "[]";
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return jsonString;
    }

    //从给定的字符串解析出数据
    private static ArrayList<BookMarkItem> readBookMarkJson(String jsonString)
    {
        ArrayList<BookMarkItem> marks = new ArrayList<BookMarkItem>();//所有书的所有书签(有可能少一个)
        //解析
        try
        {
            JSONArray bookMarksJson = new JSONArray(jsonString);
            for (int i = 0; i < bookMarksJson.length(); i++)
            {
                JSONObject currentBookMark = bookMarksJson.getJSONObject(i);
                BookMarkItem bookMarkItem = new BookMarkItem();
                bookMarkItem.path = currentBookMark.getString("path");//路径（书的标识）
                for (int j = 0; j < currentBookMark.getJSONArray("marks").length(); j++)
                {
                    int commentId =
                            currentBookMark.getJSONArray("marks").getJSONObject(j).getInt("id");
                    String commentContent =
                            currentBookMark.getJSONArray("marks").getJSONObject(j).getString("cn");
                    int commentProgress =
                            currentBookMark.getJSONArray("marks").getJSONObject(j).getInt(
                                    "pv");
                    bookMarkItem.addMark(commentId, commentContent, commentProgress);
                }
                marks.add(bookMarkItem);
            }
            //解析-------完毕--------------数据在marks里
        }
        catch (JSONException e1)
        {
            e1.printStackTrace();
        }
        return marks;
    }

    //把 表marks 格式化为string
    private static String changeToStrFromBookMarkList(ArrayList<BookMarkItem> marks)
    {
        //创建最后的结果json
        JSONArray newJsArray = new JSONArray();
        try
        {
            for (int i = 0; i < marks.size(); i++)
            {
                JSONObject jsObjBookMark = new JSONObject();
                jsObjBookMark.put("path", marks.get(i).path);
                JSONArray jsMarkArr = new JSONArray();
                for (int j = 0; j < marks.get(i).getMarksSize(); j++)
                {
                    JSONObject oneComment = new JSONObject();
                    oneComment.put("id", marks.get(i).getid(j));
                    oneComment.put("cn", marks.get(i).getComment(j));
                    oneComment.put("pv", marks.get(i).getProgress(j));
                    //oneComment.put(marks.get(i).getComment(j), marks.get(i).getProgress(j));
                    jsMarkArr.put(oneComment);
                    jsObjBookMark.put("marks", jsMarkArr);
                }
                newJsArray.put(jsObjBookMark);
            }
        }
        catch (JSONException e1)
        {
            e1.printStackTrace();
        }
        return newJsArray.toString();
    }

    //操作的文件对象
    private static File getFile(Context ctx)
    {
        File bookMarkJsonFile = new File(ctx.getFilesDir() + File.separator + "bookmark.json.asmx");
        return bookMarkJsonFile;
    }


//-----------------------------------------书签相关结束--------------------------------------------------------------
}
